package com.banciyuan.bcywebview.biz.main.mainpage.timeline;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper.OnProgressCallbacks;
import com.banciyuan.bcywebview.base.helper.access.UserAccessHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.login.LoginActivity;
import com.banciyuan.bcywebview.utils.anim.TimelineNoticeAnimation;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Timeline;
import de.greenrobot.daoexample.model.UserAccess;

public class TimelineFragment extends BaseLazyContainerFragment {

    public static final int TAG = 0;
    public static final int CIRCLE_SETTING = 1215;

    private PullToRefreashRecycleView mRefreshLv;
    private RecyclerView mContentLv;
    private TimelineListAdapter mAdapter;
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private TextView mNotice;
    private TimeLineGroundHelper mHelper;

    private List<String> timeLineKeys = new ArrayList<>();
    private LinkedList<Timeline> tlist = new LinkedList<>();

    private Timeline notice;
    private Timeline topic;
    private Timeline empty;

    private boolean is_load;
    private boolean is_end;
    private String last_time = "0";
    private String first_time = "0";
    private String score = "0";

    private boolean resetTimeline;
    private boolean clearData;

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void fetchData() {
        if (!TextUtils.isEmpty(UserDataHelper.getInstance(getActivity()).getToken())) {
            getUserAccess();
        }
        storeLastInitTimelineTime();
        initData();
        if (!TextUtils.isEmpty(UserDataHelper.getInstance(getActivity()).getToken())) {
            mHelper.getMessageData();
            mHelper.getMainSettings();
        }
    }

    public void resetTimeline() {
        resetTimeline = true;
        selfUpdateData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.timeline_layout, container, false);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void selfUpdateData() {
        mContentLv.scrollToPosition(0);
        mRefreshLv.setRefreshing();
    }

    @Override
    protected void initArgs() {
        mHelper = new TimeLineGroundHelper(getActivity());
    }

    @Override
    protected void initProgressbar(View rootView) {
        mProgressbarView = rootView.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();

            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootView) {

        mNotice = (TextView) rootView.findViewById(R.id.timeline_notice);

        mRefreshLv = (PullToRefreashRecycleView) rootView.findViewById(R.id.timeline_refresh_lv);
        mContentLv = mRefreshLv.getRefreshableView();
        mContentLv.setLayoutManager(new LinearLayoutManager(getActivity()));
        RecyclerView.ItemAnimator animator = mContentLv.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        mAdapter = new TimelineListAdapter(getActivity(), tlist);
        mAdapter.setOnRefreashClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selfUpdateData();
            }
        });

        mContentLv.setAdapter(mAdapter);
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnRefreshListener(new OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                if (!is_load)
                    if (resetTimeline || isInitTimeline()) {
                        storeLastInitTimelineTime();
                        resetData();
                        initData();
                    } else {
                        getDataHeader();
                    }
            }
        });

        mContentLv.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!is_load && !is_end) {
                    initData();
                }
            }
        });
    }

    private void storeLastInitTimelineTime() {
        SPHelper.putLong(getActivity(), SPConstant.LAST_INIT_TIMELINE_TIME, System.currentTimeMillis());
    }

    private boolean isInitTimeline() {
        long currentTime = System.currentTimeMillis();
        long duration = currentTime - SPHelper.getLong(getActivity(), SPConstant.LAST_INIT_TIMELINE_TIME, currentTime);
        return duration >= 60 * 60 * 1000;
    }

    private void resetData() {
        resetTimeline = false;
        clearData = true;
        timeLineKeys.clear();
        last_time = "0";
        first_time = "0";
        score = "0";
    }

    @Override
    protected void initData() {
        is_load = true;
        mHelper.getTimelineData(last_time, new TimelineListener() {
            @Override
            public void Succ(JSONArray array, JSONObject page, int status) {
                try {
                    String tempTime = page.getString("ntime");
                    if (first_time.equals("0")) {
                        first_time = page.getString("rtime");
                    }
                    LinkedList<Timeline> templist = TimelineFactory.createTimeline(array);
                    TimelineFactory.popIllegalItemNew(templist, clearData ? 0 : tlist.size());
                    TimelineFactory.removeDuplicate(templist, timeLineKeys);
                    LinkedList<Timeline> result = TimelineFactory.processAskTimeline(templist);
                    if (checkIsUserPost(result))
                        BaseObserver.getInstance().notifyWatchers(BaseObserver.FOCUS_USER_HAS_POST);
                    renderPullUpData(result, tempTime);
                } catch (Exception e) {
                    e.printStackTrace();
                    is_load = false;
                }
            }

            @Override
            public void fail(String reason, int status) {
                onNodataError(status);
            }
        });
    }


    private void getDataHeader() {
        is_load = true;
        mHelper.getTimelineFirstData(first_time, score, new TimelineListener() {
            @Override
            public void Succ(JSONArray array, JSONObject page, int status) {
                try {
                    LinkedList<Timeline> templist = TimelineFactory.createTimeline(array);
                    if (page != null) {
                        first_time = page.getString("since");
                        score = page.getString("score");
                    }
                    TimelineFactory.popIllegalItemNew(templist, tlist.size());
                    TimelineFactory.removeDuplicate(templist, timeLineKeys);
                    LinkedList<Timeline> result = TimelineFactory.processAskTimeline(templist);
                    if (checkIsUserPost(result))
                        BaseObserver.getInstance().notifyWatchers(BaseObserver.FOCUS_USER_HAS_POST);
                    renderPullDownData(result);
                } catch (Exception e) {
                    e.printStackTrace();
                    is_load = false;
                }
            }

            @Override
            public void fail(String reason, int status) {
                onNodataError(status);
            }
        });
    }

    public void onNetworkError() {
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onFailed();
    }

    private void renderPullUpData(LinkedList<Timeline> templist, String tempTime) {
        for (Timeline t : templist) {
            if (t.getOtype().equals("empty") && t.getOtype_data().equals("empty")) {
                is_end = true;
                break;
            }
        }
        int start = tlist.size() + 1;
        if (last_time.equals("0")) {
            memSpecial(templist);
        }
        if (clearData) {
            showInitTimelineTips();
            clearData = false;
            tlist.clear();
        }
        tlist.addAll(templist);
        if (null == mAdapter) {
            mAdapter = new TimelineListAdapter(getActivity(), tlist);
            mContentLv.setAdapter(mAdapter);
        } else {
            if (last_time.equals("0")) {
                mAdapter.notifyDataSetChanged();
            } else {
                mAdapter.notifyItemRangeInserted(start, templist.size() + 1);
            }
        }
        last_time = tempTime;
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        is_load = false;
    }

    private void showInitTimelineTips() {
        mNotice.setText(getString(R.string.timeline_refreshed));
        TimelineNoticeAnimation.setAnimation(mNotice, 0, UIUtils.dip2px(28, getActivity()));
    }

    private boolean checkIsUserPost(List<Timeline> tlist) {
        for (Timeline t : tlist) {
            if (StringUtil.notNullEqual(t.getTl_type(), "user")) {
                if (StringUtil.notNullEqual(t.getOuid(), t.getUid())) {
                    long now = System.currentTimeMillis() / 1000;
                    long time = Long.parseLong(t.getPushtime());
                    if (now - time <= 24 * 3600) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private void renderPullDownData(LinkedList<Timeline> templist) {
        if (!templist.isEmpty()) {
            if (judegeOnlyOneSpot(templist)) {
                mNotice.setText(getString(R.string.no_more_new));
            } else {
                if (judegeHasSpot(templist)) {
                    mNotice.setText(String.format(getString(R.string.new_content_nums), templist.size() - 1));
                } else {
                    mNotice.setText(String.format(getString(R.string.new_content_nums), templist.size()));
                }
            }
        } else {
            mNotice.setText(getString(R.string.no_more_new));
        }
        TimelineNoticeAnimation.setAnimation(mNotice, 0, UIUtils.dip2px(28, getActivity()));
        if (templist.size() > 0 && !judegeOnlyOneSpot(templist)) {
            if (notice != null) {
                tlist.remove(notice);
            }
            notice = addLastView();
            templist.add(notice);
        }
        if (empty != null) {
            tlist.remove(empty);
        }
        if (topic != null) {
            tlist.remove(topic);
        }
        memSpecial(templist);
        tlist.addAll(0, templist);
        if (null == mAdapter) {
            mAdapter = new TimelineListAdapter(getActivity(), tlist);
            mContentLv.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        mContentLv.scrollToPosition(0);
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        is_load = false;
    }

    private boolean judegeOnlyOneSpot(LinkedList<Timeline> templist) {
        return (templist.size() == 1 && templist.get(0).getOtype().equals(MyConstants.OTYPE_SPOT));
    }

    private boolean judegeHasSpot(LinkedList<Timeline> templist) {
        boolean flag = false;
        for (Timeline t : templist) {
            if (t.getOtype().equals(MyConstants.OTYPE_SPOT)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    private void memSpecial(List<Timeline> templist) {
        int i = 0;
        for (; i < templist.size(); i++) {
            Timeline t = templist.get(i);
            if (StringUtil.notNullEqual(t.getOtype(), MyConstants.OTYPE_SPOT)) {
                topic = templist.get(i);
            }
            if (StringUtil.notNullEqual(t.getOtype(), MyConstants.OTYPE_EMPTY)) {
                empty = templist.get(i);
            }
        }
    }

    private Timeline addLastView() {
        Timeline timeline = new Timeline();
        timeline.setOtype(MyConstants.OTYPE_LAST_VIEW);
        timeline.setOtype_data(MyConstants.OTYPE_LAST_VIEW);
        return timeline;
    }

    private void onNodataError(int status) {
        if (status == 0 || status == 10) {
            if (null != mAdapter) {
                mAdapter.notifyDataSetChanged();
            }
            mProgressbarHelper.onNodata(getString(R.string.base_progressbar_nodata), true);
        } else if (status == 100) {
            try {
                UserDataHelper.Logout(getActivity(), new UserDataHelper.ClearAliasCallBack() {
                    @Override
                    public void doclear() {
                        gotoUtil.gotoAct(getActivity(), LoginActivity.class);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            gotoUtil.gotoAct(getActivity(), LoginActivity.class);
        }
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onNodata();
        is_load = false;
    }

    private void getUserAccess() {
        String url = HttpUtils.BASE_URL + UserApi.getUserAccessList();
        List<BcyPair> paris = new ArrayList<>();
        paris.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        Map<String, String> map = HttpUtils.getData(paris);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<UserAccess> ulist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<UserAccess>>() {
                        }.getType());
                        UserAccessHelper.updateUserAccess(getActivity(), gson.toJson(ulist));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        };
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        VolleyQueue.getRquest(getActivity()).add(stringRequestParam);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CIRCLE_SETTING) {
            if (mAdapter != null) {
                mAdapter.notifyItemChanged(0);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mAdapter) {
            mAdapter.destoryObserver();
        }
    }
}